package com.qf.mybatis.utils;/*
*王浩政 
*whz
2022/8/31
11:30
*小米商城
*/
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
public class MybatisUtils {
    private static ThreadLocal<SqlSession> threadLocal=new ThreadLocal<>();
    private static SqlSessionFactory sqlSessionFactory;
    static {
        try {
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis.xml"));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    /*
 * 这个是获取连接的
 * */
    public static SqlSession openSession(){
        //创建并保存到threadlocal
        SqlSession sqlSession = sqlSessionFactory.openSession();
        threadLocal.set(sqlSession);
        return sqlSession;
    }

    /*
    *提交事务
    * */
    public static void commit(){
        SqlSession sqlSession = threadLocal.get();
        if(sqlSession!=null){
            sqlSession.commit();
        }
    }
    /*
    * 回滚事务
    * */
    public static void roolback(){
        SqlSession sqlSession = threadLocal.get();
        if(sqlSession!=null){
            sqlSession.rollback();
        }
    }

    /*
    * 关闭连接
    * */
    public static void close(){
        SqlSession sqlSession = threadLocal.get();
        if(sqlSession!=null){
            sqlSession.close();
            //移除，防止内存泄露
            threadLocal.remove();
        }
    }

    /*
    * 获取Mapper对象
    * */
    public static <T> T getMapper(Class<T> clazz){
        SqlSession sqlSession = threadLocal.get();
        //没有就创建
        if(sqlSession==null){
            //创建一个并保存
             sqlSession = openSession();
             threadLocal.set(sqlSession);
        }
        //返回mapper
        return sqlSession.getMapper(clazz);
    }
}
